package www.lagou.app;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;
import www.lagou.entity.Account;
import www.lagou.utils.DruidUtils;

import java.sql.SQLException;
import java.time.LocalDateTime;


/**
 * 转账实现的各种方法，使用queryRunner操作数据
 */
public class Transaction {


    /**
     * 获取账号信息的方法
     * @param name
     * @return
     * @throws SQLException
     */
    public static Account getAccount(String name) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "SELECT * FROM account WHERE username = ?";
        Account account = queryRunner.query(sql, new BeanHandler<>(Account.class), name);
        System.out.println(account);
        return account;

    }

    /**
     * 实现转账的方法
     * @param tranMoney
     * @param card
     * @throws SQLException
     */
    public static void transact(Double tranMoney,String card) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "update account set balance = ? where card = ?";
        Object[] param = {tranMoney,card};
        queryRunner.update(sql,param);
    }



    /**
     * 实现转账交易记录入库的方法
     * @param cardId
     * @param traType
     * @param tranMoney
     * @param date
     * @throws SQLException
     */
    public static void setTransact(String cardId, String traType, double tranMoney, LocalDateTime date) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "insert into TRANSACTION" +
                "(cardid, tratype, tramoney, tradate)" +
                " values(?,?,?,?)";
        Object[] param = {cardId, traType, tranMoney, date};
        queryRunner.update(sql,param);

    }
}
